import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './zjc.module.css';
import { useDispatch } from "react-redux";
import { DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { LangEn } from "@/utils/langEn";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import ZjcUtil from "@/utils/zjcUtil";
import AppParams from "@/utils/appParams";
import { doLogin } from "@/store/actions/login";

/**
 * 登录页
 */
export default function ZjcInput() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    // zjc 输入内容
    const [zjcValue, setZjcValue] = useState('')

    // 文案翻译
    const [curLang, setCurLang] = useState(LangEn);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false)

        //打点
        doHitEvent("ZJC_INPUT_START")

        return () => {
            //打点
            doHitEvent("ZJC_INPUT_END")
        }
    }, [])

    // 点击提交
    const onHandleSubmit = () => {
        console.log("点击提交");

        // 判断是否选全对
        if (zjcValue.length > 0) {
            // 缓存
            ZjcUtil.zjc = zjcValue;

            // 直接登录
            let inputResult = isInputCorrect();
            if (!inputResult) {
                history.replace('/register');
                return;
            }

            // 登录
            doUserLogin(inputResult.mobile, inputResult.password, inputResult.email, ZjcUtil.ipInfo || {});

        } else {
            Toast.show(curLang.zjcVerifyVerificationFailedPleaseTryAgain);
        }
    };

    // 登录返回
    const onDoUserLoginCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('登录返回: ' + success);

        if (success && data) {
            // 处理流程业务
            console.log('跳转首页');
            history.replace('/home');
        }
    };

    // 输入内容监听
    const onHandleInputChange = (e) => {
        setZjcValue(e.target.value);
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    //请求登录接口
    const doUserLogin = async (mobile, password, email, ipInfo) => {
        console.log("doLogin: " + mobile + " , " + password + " , " + email);

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const referrerCode = AppParams.referrer
            const tzCode = Intl.DateTimeFormat().resolvedOptions().timeZone;
            const action = doLogin(mobile, password, email, referrerCode || "", ipInfo || {}, tzCode || "", onDoUserLoginCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }


    // 判断输入是否合法
    const isInputCorrect = () => {
        //验证手机号
        let mobile = ZjcUtil.mobile;

        //验证密码
        let password = ZjcUtil.password;

        //验证密码
        let email = ZjcUtil.email;

        if (!mobile || (mobile.length <= 0)) {
            return null;
        }

        if (!password || (password.length < 8)) {
            return null;
        }

        return { mobile: mobile, password: password, email: email };
    };
    return (
        <div className="pageRoot pageContentPaddingHorizontal16px">
            {/* <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}></NavigateBar> */}

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            {/* 标题 */}
            <div className={styles.zjcTitleLarge}>{curLang.zjcInputImportWallet}</div>

            {/* zjc 列表 */}
            <div className={styles.zjcVerifyList}>
                {/* 第1行 */}
                <div className={styles.zjcListVerifyContent}>
                    <textarea
                        className={styles.zjcListInputContent}
                        value={zjcValue}
                        onChange={onHandleInputChange}
                        placeholder={curLang.zjcInputTips}
                    />
                </div>
            </div>

            {/* 提交 */}
            <div className="pageBtnSubmit pageMarginTop16px" onClick={onHandleSubmit}>{curLang.zjcInputNext}</div>

            {/* 底部提示 */}

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}